package cn.com.pajx.pajx_visitor_v3.service;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;

import androidx.annotation.Nullable;

import cn.com.pajx.pajx_visitor_v3.utils.DateUtil;
import cn.com.pajx.pajx_visitor_v3.utils.LogUtils;


/**
 * Created by ruancw on 2024/2/28.
 * 执行定时任务
 */

public class AlarmService extends Service {
    public static String ACTION_ALARM = "action_alarm";
    private final Handler mHandler = new Handler(Looper.getMainLooper());
    private final Intent intent = new Intent("com.pajx.alarm.RECEIVER");
    private boolean isSendBroadcast = false;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new Binder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //启动定时任务
        startAlarmTask();
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 启动定时任务管理器执行定时
     */
    private void startAlarmTask() {
        //解决定时任务首次加载数据的问题，第一次默认不加载
        if (isSendBroadcast) {
            mHandler.post(() -> {
                //执行定时任务
                sendBroadcast(intent);
            });
        }

        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Intent alarmIntent = new Intent(this, AlarmService.class);
        alarmIntent.setAction(AlarmService.ACTION_ALARM);
        @SuppressLint("UnspecifiedImmutableFlag")
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        LogUtils.e("alarm_task_start=" + DateUtil.getCurrentYMDHMS());
        isSendBroadcast = true;
        //设置周期为5分钟
        assert am != null;
        int MINUTE = 5 * 60 * 1000;//间隔5分钟
        am.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + MINUTE, pendingIntent);
    }

}
